package com.gitee.cashzhang27.test.boot.other.filter;

import cn.hutool.json.JSONUtil;
import com.gitee.cashzhang27.test.boot.other.constant.LogConstants;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 控制器增强，在响应返回之前，可以获取RequestMapping注解方法的返回结果
 *
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/06/14 15:16
 */
@ControllerAdvice
public class ControllerResponseAdvice implements ResponseBodyAdvice {

  @Override
  public boolean supports(@Nullable MethodParameter methodParameter, @Nullable Class aClass) {
    return true;
  }

  @Override
  public Object beforeBodyWrite(@Nullable Object obj, @Nullable MethodParameter methodParameter,
      @Nullable MediaType mediaType, @Nullable Class aClass,
      @Nullable ServerHttpRequest serverHttpRequest,
      @Nullable ServerHttpResponse serverHttpResponse) {
    if (obj != null) {
      try {
        // 在这里可以修改返回参数
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) serverHttpRequest)
            .getServletRequest();
        servletRequest.setAttribute(LogConstants.RES_BODY, JSONUtil.toJsonStr(obj));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return obj;
  }
}
